<!--
 * @Descripttion: 生成对账单
 * @version:
 * @Author: 张文韬
 * @Date: 2020-10-13 11:49:35
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-26 17:46:32
-->
<template>
  <el-card class="box-card">
    <div class="control-box">
      <!-- search 搜索区 START -->
      <e-search ref="searchFormRef" :form-options="formOptions"
                :form-label-width="searchLabelWidth"
                :refresh-show="true"
                @on-search="searchControlHandle"
                @on-refresh="refreshControlHandle"
                @change-height="changeControlHeight" />
      <!-- search 搜索区 END -->
    </div>
    <!-- 功能按钮区 START -->
    <el-row class="options-Area" type="flex" justify="end">
      <el-button @click="downSyncSupplierBillExcel" type="primary" size="small">导出同步供应商账单</el-button>
      <el-button @click="handleSyncSupplierBills" type="primary" size="small">同步供应商账单</el-button>
      <el-button @click="downExcel" type="primary" size="small">下载模板</el-button>
      <el-upload
          class=""
          :headers="fileConfig"
          :action="uploadUrl"
          multiple
          :limit="1"
          :file-list="fileList"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
          :on-exceed="handleExceed">
        <el-button class="upload-btn" type="primary" size="small">导入对账单</el-button>
      </el-upload>
      <el-button @click="handleTriggerReconciliation()" type="primary" size="small">触发对账</el-button>
    </el-row>
    <div class="table-box">
      <!-- table 数据表格 START -->
      <e-table :data="tableData"
               :columns="columns"
               stripe
               border
               :max-height="tableMaxHeight"
               style="width: 100%"
               @selection-change="changeTableSelectData"
               :current="pageData.pageNum"
               :total="pageData.total"
               @page-size-change="changePageSize"
               @page-current-change="changePageCurrent">
      </e-table>
      <!-- table 数据表格 END -->
    </div>
    <!-- editDialog 编辑弹窗 START -->
    <el-dialog title="不参与对账原因"
               :visible.sync="editDialogShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               width="50%">
      <el-input
          type="textarea"
          show-word-limit
          :rows="2"
          maxlength="1000"
          placeholder="请输入不参与对账原因"
          v-model="noCheckReason">
      </el-input>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="cancelDialogDataHandle">取 消</el-button>
        <el-button type="primary"
                   @click="saveDialogDataHandle">确 定</el-button>
      </span>
    </el-dialog>
    <!-- editDialog 编辑弹窗 END -->
  </el-card>
</template>

<script>
import eForm from '@/components/e-form'
import { formOptions, btns } from './control'
import columns from './columns'
import eSearch from '@/components/e-search'
import {
  queryRecordList,
  syncSupplierBills,
  signNoCheck,
  triggerRecord,
  suppliersForSelfOperatedPrice
} from '@/api/admin.api'
import {exportCenterSync,exportReconciliation} from '@/api/supplier.api'
// 上传文件
import fileUpdata from '@/api/file.config'
import { beforeUpload } from '@/util/common'
import moment from 'moment'
const baseUrl = process.env.VUE_APP_BASE_API
import { Loading } from 'element-ui'
export default {
  name: 'generate-record',
  components: {
    eForm,
    eSearch
  },
  props: {},
  data () {
    return {
      formOptions,
      btns,
      columns,
      // editFormOptions,
      // editFormRules,
      // interFaces,
      searchLabelWidth: '100px',
      editFormLabelWidth: '100px',

      // 编辑框是否展示
      editDialogShow: false,
      // 编辑框表单数据
      dialogFormCurrent: {},
      // 查询表单
      searchFormData: {},
      // 控制区高度
      controlHeight: 0,
      // 表格数据
      tableData: [],
      // 分页数据
      pageData: {
        // 当前分页
        pageNum: 1,
        // 分页条数
        pageSize: 10,
        // 数据总数
        total: 0
      },
      // 表格选中数据
      tableSelectData: [],
      // 附件列表
      fileList: [],
      fileConfig:  fileUpdata.headers(),
      // 不参与对账原因
      noCheckReason: '',
      uploadUrl: `${baseUrl}/api/order/reconciliation/centerImport`,
    }
  },
  watch: {},
  computed: {
    // 组合查询条件和分页
    searchData () {
      const { pageNum, pageSize } = this.pageData
      return { ...this.searchFormData, size: pageSize, current: pageNum }
      // return Object.assign(this.searchFormData,{size: pageSize},{current:pageNum})
    },
    // 表单实例
    dialogForm () {
      return this.$refs.dialogForm
    },
    //表格最大高度
    tableMaxHeight () {
      return window.innerHeight - this.controlHeight - 260
    }
  },
  created () {
    this.init()
  },
  methods: {
    /**
     * @functionName init
     * @description 页面初始化
     * @author 张航
     * @date 2020-09-09 08:40:06
     * @version V1.0.0
     */
    init () {
      this.getTableData()
      this.getLabelData()
    },
    // 获取菜单弹出项
    getLabelData () {
      suppliersForSelfOperatedPrice().then((res)=>{
        res.map((item, index) => {
          const optionObj = {}
          optionObj.value = item.supplierId
          optionObj.label = item.supplierName
          this.$set(this.formOptions[0].options, index, optionObj)
        })
      })
      // // 获取电商筛选类型
      // querySuppliers().then(res => {
      //  // console.log(res)
      //   res.map((item, index) => {
      //     const optionObj = {}
      //     optionObj.value = item.id
      //     optionObj.label = item.orgNameZhShort
      //     this.$set(this.formOptions[0].options, index, optionObj)
      //   })
      // })
    },
    /**
     * @functionName searchControlHandle
     * @param {Object} data 查询参数
     * @description 查询
     * @author 张航
     * @date 2020-09-08 15:01:26
     * @version V1.0.0
     */
    searchControlHandle (data) {
      data.orderStartTime?data.orderStartTime = moment(data.orderStartTime).format('YYYY-MM-DD 00:00:00') : ''
      data.orderEndTime?data.orderEndTime = moment(data.orderEndTime).format('YYYY-MM-DD 23:59:59') : ''
      this.searchFormData = data
      // console.log(data)
      this.refreshPageCurrent()
    },
    /**
     * @functionName refreshControlHandle
     * @param {Object} data 重置后的数据
     * @description 重置查询条件
     * @author 张航
     * @date 2020-09-08 17:01:51
     * @version V1.0.0
     */
    refreshControlHandle (data) {
      // console.log(data)
      this.searchFormData = data
    },
    /**
     * @functionName changeControlHeight
     * @param {String} height 控制区占用高度
     * @description 控制区高度变化
     * @author 张航
     * @date 2020-09-16 16:17:07
     * @version V1.0.0
     */
    changeControlHeight (height) {
      this.controlHeight = height
    },
    /**
     * @functionName changeTableSelectData
     * @param {Array} rows 选中数据
     * @description 表格选中数据改变
     * @author 张航
     * @date 2020-09-08 17:52:12
     * @version V1.0.0
     */
    changeTableSelectData (rows) {
      this.tableSelectData = rows
    },
    /**
     * @functionName checkTableSelectData
     * @return {Number} 返回结果
     * @description 方法描述
     * @author 张航
     * @date 2020-09-10 09:58:59
     * @version V1.0.0
     */
    checkTableSelectData () {
      if (this.tableSelectData.length === 0) {
        this.$alert('至少选择一条数据！', '提示', {
          confirmButtonText: '确定'
        })
      }
      return this.tableSelectData.length
    },
    /**
     * @functionName changePageSize
     * @param {Number} size 分页条数
     * @description 修改分页条数
     * @author 张航
     * @date 2020-09-08 17:57:06
     * @version V1.0.0
     */
    changePageSize (size) {
      this.pageData.pageSize = size
      this.getTableData()
    },
    /**
     * @functionName changePageCurrent
     * @param {Number} current 当前分页
     * @description 修改当前分页
     * @author 张航
     * @date 2020-09-08 18:02:03
     * @version V1.0.0
     */
    changePageCurrent (current) {
      this.pageData.pageNum = current
      this.getTableData()
    },
    /**
     * @functionName refreshPageCurrent
     * @description 重置当前分页
     * @author 张航
     * @date 2020-09-22 10:45:57
     * @version V1.0.0
     */
    refreshPageCurrent () {
      this.pageData.pageNum = 1
      this.getTableData()
    },
    /**
     * @functionName getTableData
     * @description 获取表格数据
     * @author 张航
     * @date 2020-09-08 17:59:45
     * @version V1.0.0
     */
    getTableData () {
      // console.log(this.searchData)
      queryRecordList(this.searchData).then(res => {
        this.tableData = res.records
        this.pageData.total = res.total
      })
    },
    /**
     * @functionName openDialog
     * @description 打开编辑框
     * @author 张航
     * @date 2020-09-08 11:38:51
     * @version V1.0.0
     */
    openDialog () {
      this.editDialogShow = true
    },
    /**
     * @functionName closeDialog
     * @description 关闭编辑框
     * @author 张航
     * @date 2020-09-08 14:27:02
     * @version V1.0.0
     */
    closeDialog () {
      this.editDialogShow = false
    },
    /**
     * @functionName saveDialogData
     * @description 保存弹框数据
     * @author 张文韬
     * @date 2020-10-25 14:12:09
     * @version V1.0.0
     */
    saveDialogDataHandle () {
      const reson = this.noCheckReason
      if (reson.length > 0) {
        const tempData = this.tableSelectData
        let ids = []
        tempData.map((item) => {
          ids.push(item.supplierOrderNo)
        })
        signNoCheck({
          orderIdList: ids,
          reason: reson,
          type: 'center'
        }).then(res => {
          this.closeDialog()
          this.getTableData()
          this.$message({
            message: '保存成功',
            type: 'success'
          })
        })
      }
    },
    /**
     * @functionName cancelDialogData
     * @description 取消保存弹框数据
     * @author 张文韬
     * @date 2020-10-25 14:33:06
     * @version V1.0.0
     */
    cancelDialogDataHandle () {
      this.noCheckReason = ''
      this.closeDialog()
    },
    /**
    * @functionName downSupplierSyncBillExcel
    * @desccription 导出同步供应商账单
    * @author 穆宏宇
    * @date 2021-04-19 09:41:37
    * @version v1.0.0
    */
    downSyncSupplierBillExcel () {

      let searchData = this.$refs.searchFormRef.formData
      searchData.orderStartTime?searchData.orderStartTime = moment(searchData.orderStartTime).format('YYYY-MM-DD 00:00:00') : ''
      searchData.orderEndTime?searchData.orderEndTime = moment(searchData.orderEndTime).format('YYYY-MM-DD 23:59:59') : ''
      exportCenterSync(searchData).then((res) => {
        let blob = new Blob([res], { type: "application/vnd.ms-excel" });
        this.saveAs(blob, "同步供应商账单.xlsx");
      });
    },
    /**
     * @functionName handleSyncSupplierBills
     * @description 同步供应商账单
     * @author 张文韬
     * @date 2020-10-25 14:28:32
     * @version V1.0.0
     */
    handleSyncSupplierBills () {
      let searchData = this.$refs.searchFormRef.formData
      searchData.orderStartTime?searchData.orderStartTime = moment(searchData.orderStartTime).format('YYYY-MM-DD 00:00:00') : ''
      searchData.orderEndTime?searchData.orderEndTime = moment(searchData.orderEndTime).format('YYYY-MM-DD 23:59:59') : ''
      // console.log(searchData)
      syncSupplierBills(searchData).then(res => {
       // console.log(res)
        if (res) {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.getTableData()
        }
        else {
          this.$message({
            message: '操作失败',
            type: 'warning'
          })
        }
      })
    },
    // 触发对账
    handleTriggerReconciliation () {
      const searchData = this.$refs.searchFormRef.formData
      searchData.orderStartTime?searchData.orderStartTime = moment(searchData.orderStartTime).format('YYYY-MM-DD 00:00:00') : ''
      searchData.orderEndTime?searchData.orderEndTime = moment(searchData.orderEndTime).format('YYYY-MM-DD 23:59:59') : ''
      // console.log(searchData)
      triggerRecord(searchData).then(res => {
        // if (res) {
          this.$message({
            message: '对账成功',
            type: 'success'
          })
          this.$router.push({ path:'/trigger-record',query: {type: res} })
        // }
        // else {
          // this.$message({
          //   message: '对账失败',
          //   type: 'warning'
          // })
        // }
      }).catch(err=>{
        this.$message({
            message: '对账失败',
            type: 'warning'
          })
      })
    },
    // 处理点击不参与对账
    handleNoReconciliation () {
      if (this.checkTableSelectData() > 0) {
        this.openDialog()
      }
    },
    // 提交检测判断
    handleExceed(files, fileList) {
      this.$message.warning(`最多可上传 1 个附件，您已超限`)
    },
    beforeUpload(file) {
      this.loading = Loading.service({text: '文件上传中...',})
      const isLt500M = file.size / 1024 / 1024 < 500
      if (!isLt500M) {
        this.$message.error('上传附件大小不能超过 500MB!')
        this.loading.close()
      }
      return isLt500M
    },
    // 文件上传成功
    // handleUploadSuccess(res, file) {
    //   const curFile = {
    //     name: res.data.submittedFileName,
    //     url:res.data.url,
    //     id:res.data.id,
    //     fileType:res.data.fileType
    //   }
    //   this.fileList.push(curFile)
    // },
    // // 文件上传失败
    // handleUploadError(res, file) {
    //   this.$message.error("文件上传失败，请重试")
    // },
    // 文件上传成功
    handleUploadSuccess(res, file) {
      // const curFile = {
      //   name: res.data.submittedFileName,
      //   url:res.data.url,
      //   id:res.data.id,
      //   fileType:res.data.fileType
      // }
      // this.fileList.push(curFile)
      if (res.data==='true') {
        this.$message.success('上传成功！')
      }else{
        this.$message.warning(res.msg||'上传失败！')
      }
      this.fileList = []
      this.loading.close()
    },
    // 文件上传失败
    handleUploadError(res, file) {
      let result = JSON.parse(res.message)
      this.$message.warning(result.msg||'上传失败！')
      this.fileList = []
      this.loading.close()
    },
    // 下载文件
    downExcel(){
      exportReconciliation().then((res) => {
        let blob = new Blob([res], { type: "application/vnd.ms-excel" });
        this.saveAs(blob, "对账单录入模板.xlsx");
      });
    },
    saveAs(blob, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(blob, filename);
      } else {
        var link = document.createElement("a");
        var body = document.querySelector("body");
        link.href = window.URL.createObjectURL(blob);
        link.download = filename;
        link.style.display = "none";
        body.appendChild(link);
        link.click();
        body.removeChild(link);
        window.URL.revokeObjectURL(link.href);
      }
    },
  },
  mounted () { }
}
</script>
<style lang="scss">
.box-card {
  margin: 4px;
  height: calc(100vh - 110px);
  .el-card__body {
    padding: 0;
  }
  .upload-btn {
    margin: 0 10px;
  }
}
.abc-header {
  color: #0000ff;
}

.control-box {
  margin-bottom: 10px;
}
.options-Area{
  margin-bottom: 10px;
}
</style>
